package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //获取请求的路径
        String uri = request.getRequestURI();

        log.info("拦截到的资源为 {}",uri);
        Long empId = (Long) request.getSession().getAttribute("emp");
        if (empId!=null){
            //用户登陆了才能存,储存session中的id对象值到threadLocal对象中
            BaseContext.currentSetId(empId);
            //登录了
            return true;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId!=null){
            //用户登陆了才能存,储存session中的id对象值到threadLocal对象中
            BaseContext.currentSetId(userId);
            //登录了
            return true;
        }
        //未登录
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }
}
